﻿import com.dmotiko.mirador.*
import com.dmotiko.general.*
import mx.data.encoders.Bool;
import mx.utils.Delegate;

class MiradorSound
extends BaseClip {
	
	private var mcBars:MovieClip;
	private var mcPlay:MiradorInternalBtn;
	private var mcStop:MiradorInternalBtn;
	private var bPaused:Boolean;
	private var music:Sound;
	private var nLastPosition:Number;
	private var musicCheck:MovieClip;
	
	private function initClip():Void {
		MiradorSite.getApp().setMiradorSound(this);
		MiradorSite.getApp().addEventListener( WebSite.SOUND_CHANGED, Delegate.create(this, sound_changed));
		
		music = new Sound();
		music.loadSound("music.mp3", true);
						
		music.onSoundComplete = function() {
			this.start(0);
		}
	}
	
	public function pauseMusic(b:Boolean, watch:Object):Void {
		bPaused = b;
		if (b) {
			nLastPosition = music.position;
			music.stop();
		} else {
			music.start( nLastPosition / 1000 );
		}
		if (b && watch) {
			var clip:MovieClip = this.createEmptyMovieClip("watcher", this.getNextHighestDepth());
			var root = this;
			clip.onEnterFrame = function() {
				if (watch instanceof Object == false) {
					delete this.onEnterFrame;
					if(MiradorSite.getApp().getSound()) root.pauseMusic(false);
					removeMovieClip(this);
				}
			}
		}
	}
	
	private function sound_changed( event ):Void {
		if ( MiradorSite.getApp().getSound() ) {
			mcStop.setActive(false, true);
			mcPlay.onRollOver();
			mcPlay.setActive(true);
			mcBars.gotoAndStop(2);
			pauseMusic(false);
			
		} else {
			mcPlay.setActive(false, true);
			mcStop.onRollOver();
			mcStop.setActive(true);
			mcBars.gotoAndStop(1);
			pauseMusic(true);
			
		}
	}
	
	function childLoaded( e ):Void {
		if ( e.target == mcPlay ) {
			mcPlay.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, toggle_snd) );
			mcPlay.onRollOver();
			mcPlay.onRelease();
			
		} else if ( e.target == mcStop) {
			mcStop.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, toggle_snd) );
			
		}
	}
	
	private function toggle_snd( e ):Void {
		if ( e.target == mcPlay) {
			MiradorSite.getApp().setSound(true);
			
		} else {
			MiradorSite.getApp().setSound(false);
			
		}
	}
	
}